#include "List.h"

QueueInfo NetworkQueueMsg;

void QueueInit(void)
{
    memset(&NetworkQueueMsg, 0, sizeof(NetworkQueueMsg));
}

BOOLEAN CreateQueue(QueueInfo *Queue,INT16U Data, INT8U Instruction)
{
    LIST *New;

    if(Queue->NetworkNum != 0)
    {
        return false;
    }

    New = malloc(sizeof(LIST));

    if(New == NULL)
    {
        return false;
    }

    Queue->CurrentTask = New;
    New->Data = Data;
    New->Instruction = Instruction;
    New->Next = NULL;
    New->Last = NULL;

    Queue->NetworkNum++;

    return true;
}


BOOLEAN EnterQueue(QueueInfo *Queue,INT16U Data, INT8U Instruction)
{
    LIST *New;

    New = malloc(sizeof(LIST));

    if(New == NULL)
    {
        return false;
    }

    if(Queue->CurrentTask == NULL)
    {
        CreateQueue(Queue, Data, Instruction);
        Queue->NetworkNum = 1;
        return true;
    }

    if(Queue->CurrentTask->Next == NULL)
    {
        New->Data = Data;
        New->Instruction = Instruction;
        New->Next = Queue->CurrentTask;
        New->Last = Queue->CurrentTask;

        Queue->CurrentTask->Last = New;
        Queue->CurrentTask->Next = New;
    }
    else
    {
        New->Data = Data;
        New->Instruction = Instruction;
        New->Next = Queue->CurrentTask;
        New->Last = Queue->CurrentTask->Last;

        New->Last->Next = New;
        New->Next->Last = New;
    }
    Queue->NetworkNum++;

    return true;
}


BOOLEAN ExitQueue(QueueInfo *Queue)
{
    LIST *Exit;

    Exit = Queue->CurrentTask;

    if(Exit == NULL)
    {
        return false;
    }

    if(Exit->Last == NULL)
    {
        free(Exit);
        Queue->CurrentTask = NULL;
        Queue->NetworkNum = 0;
    }
    else if(Queue->NetworkNum == 2)
    {
        Exit->Last->Next = NULL;
        Exit->Last->Last = NULL;
        Queue->CurrentTask = Exit->Last;
        Queue->NetworkNum = 1;
        free(Exit);
    }
    else
    {
        Exit->Last->Next = Exit->Next;
        Exit->Next->Last = Exit->Last;
        Queue->NetworkNum--;
        Queue->CurrentTask = Exit->Next;
        free(Exit);
    }

    return true;
}
